package com.jee.ssm.common.utils.hik;

import com.alibaba.fastjson.JSONObject;

import java.security.MessageDigest;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Random;
import java.util.Set;


public class CommonUtil {

	/**
	 * 签名算法,获取token
	 * @param jsonStr
	 * @param secret
	 * @return
	 */
	public static String getToken(String jsonStr,String secret){
		JSONObject jsonObject = JSONObject.parseObject(jsonStr);
		return getToken(jsonObject,secret);
	}

	/**
	 *
	 * @Description: 签名算法
	 * @param jsonObject
	 * @param secret
	 * @return
	 */
	private static String getToken(JSONObject jsonObject, String secret){
		ArrayList<String> list = new ArrayList<String>();
		Set <String> keys = jsonObject.keySet();
		for (String key : keys) {
			String value = jsonObject.getString(key);
			if(value!=null && !"".equals(value)){
				list.add(key + "=" + value + "&");
			}
		}
		Collections.sort(list, String.CASE_INSENSITIVE_ORDER);
		StringBuilder sb = new StringBuilder();
		for(int i = 0; i < list.size(); i ++) {
			sb.append(list.get(i));
		}
		String result = sb.toString();
		result += "secret=" + secret;
		return getStringMD5(result).toUpperCase();
	}

	/**
	 * 获取32位的随机字符串
	 * @return 一定长度的字符串
	 */
	public static String getNonce() {
		String base = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
		Random random = new Random();
		StringBuffer sb = new StringBuffer();
		for (int i = 0; i < 32; i++) {
			int number = random.nextInt(base.length());
			sb.append(base.charAt(number));
		}
		return sb.toString();
	}

	/**
	 * Hex 常量表
	 */
	private static final char hexDigits[] = {
			'0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
			'a', 'b', 'c', 'd', 'e', 'f'
	};
	/**
	 * 计算字符串的MD5值
	 *
	 * @param text 要计算MD5的字符串
	 * @return MD5字符串
	 */
	public static String getStringMD5(final String text) {
		return getStringMD5(text,"UTF-8");
	}

	/**
	 * 计算字符串的MD5值
	 *
	 * @param text 要计算MD5的字符串
	 * @return MD5字符串
	 */
	public static  String getStringMD5(final String text,String charset) {

		String md5String = "";
		try {
			byte arrByte[] = text.getBytes(charset);
			MessageDigest messageDigest = MessageDigest.getInstance("MD5");
			messageDigest.update(arrByte);
			byte arrMD5Byte[] = messageDigest.digest();
			char arrChar[] = new char[arrMD5Byte.length * 2];
			int i = 0;
			for (byte b : arrMD5Byte) {
				arrChar[i++] = hexDigits[b >>> 4 & 0xf];
				arrChar[i++] = hexDigits[b & 0xf];
			}
			md5String = new String(arrChar);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return md5String;
	}

}
